/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.e2e.haiti.infrastructure.surveyor;

import java.io.File;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;



/**
 * Demonstrates combining a TabHost with a ViewPager to implement a tab UI
 * that switches between tabs and also allows the user to perform horizontal
 * flicks to move between the tabs.
 */
public class Exterior extends SherlockFragmentActivity {
	
    public static Utils utilsHelper = null;
    private Cursor structureCursor = null;
    public static int structureID;
    
    private static final int EXTERIOR_PHOTOS_TAB = 0;
    private static final int EXTRA_PHOTOS_TAB = 1;

    private static final int STRUCTURE_NOTE_DIALOG_ID = 0;

    private static final int NOTES_ACTION_MENU = 0;
    private static final int NEXT_ACTION_MENU = 1;
    
    private static final int CAPTURE_IMAGE_FRONT = 0;
    private static final int CAPTURE_IMAGE_RIGHT = 1;
    private static final int CAPTURE_IMAGE_BACK = 2;
    private static final int CAPTURE_IMAGE_LEFT = 3;

    
    TabHost mTabHost;
    ViewPager  mViewPager;
    TabsAdapter mTabsAdapter;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        menu.add(0,NOTES_ACTION_MENU,0, "Notes")
        .setIcon(R.drawable.notes)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 

        menu.add(0,NEXT_ACTION_MENU,0, "Next")
            .setIcon(R.drawable.next)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        
       return true; 
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        structureID = getIntent().getIntExtra("structureID", -1); //Get structureID otherwise -1  
        utilsHelper = new Utils(this);      
        structureCursor = utilsHelper.getStructureCursor(structureID);
        
        // Sets the title on the action bar to the be the name of the structure
        String structureTitle = " " + structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NAME)) + " Questionnaire";
        setTitle(structureTitle);   
        
        // Sets the view of the base activity
        setContentView(R.layout.fragment_tabs_pager);
        mTabHost = (TabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup();

        mViewPager = (ViewPager)findViewById(R.id.pager);

        mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

        // TABS are created and linked to various classses
//         "q"+Integer.toString(DEMOGRAPHICS_TAB) is a way of specifiy q0,q1,q2 TAGS that may be accessed. These tags are currently not used
        mTabsAdapter.addTab(mTabHost.newTabSpec("q"+Integer.toString(EXTERIOR_PHOTOS_TAB)).setIndicator("Exterior Photos"),
                FragmentExteriorPhotos.class, null);
        mTabsAdapter.addTab(mTabHost.newTabSpec("q"+Integer.toString(EXTRA_PHOTOS_TAB)).setIndicator("Extra Photos"),
        		FragmentExtraPhotos.class, null);
        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case NOTES_ACTION_MENU:
            	showDialog(STRUCTURE_NOTE_DIALOG_ID);           	                       	            
                return true;  
            case NEXT_ACTION_MENU:
            	
                int tabID = mTabHost.getCurrentTab();
                
                // If its not the first time the application enters the Questionnaire tab, update the Formd data to the database
                    Fragment f = (Fragment) mViewPager.getAdapter().instantiateItem(mViewPager, tabID);
                	updateFormDataDB(f.getView() , tabID);
                	//updateFormDataDB(getItem(position).getView());            
            	
	            utilsHelper.startNextActivity(structureID, StructureList.class);
                return true;         
                
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mTabHost.getCurrentTabTag());
    }
    
    /**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between pages.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct paged in the ViewPager whenever the selected
     * tab changes.
     */
    
    
    public static class TabsAdapter extends FragmentPagerAdapter
            implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final TabHost mTabHost;
        private final ViewPager mViewPager;
        public int previousTabID = -1; // initialized to -1 when no tabs are selected
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final String tag;
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mTabHost = tabHost;
            mViewPager = pager;
            mTabHost.setOnTabChangedListener(this);
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);
            mTabs.add(info);
            mTabHost.addTab(tabSpec);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        // Positon is integer 0-N indiciating which tab
        // tabID is the lowercase name of the Tab
        public void onTabChanged(String tabId) {
            int position = mTabHost.getCurrentTab();
            
            // If its not the first time the application enters the Questionnaire tab, update the Formd data to the database
            if (previousTabID != -1) {
                Fragment f = (Fragment) mViewPager.getAdapter().instantiateItem(mViewPager, previousTabID);
            	Exterior.updateFormDataDB(f.getView(),previousTabID);
            	//updateFormDataDB(getItem(position).getView());
            }
                        
            previousTabID = position; // initialized to -1 when first enter into Questionnaire class
            mViewPager.setCurrentItem(position);

        }
        
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            // Unfortunately when TabHost changes the current tab, it kindly
            // also takes care of putting focus on it when not in touch mode.
            // The jerk.
            // This hack tries to prevent this from pulling focus out of our
            // ViewPager.
            TabWidget widget = mTabHost.getTabWidget();
            int oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    } // End of Tabs Adapter
    
 public static void updateFormDataDB(View v, int TabID){
    	
    	// Switches to the correct DB update information given the previous tab
   switch (TabID){
   
   		case EXTERIOR_PHOTOS_TAB: 
   	// 4 Exterior Photos ==============================================================================
   			// Declares the text input fields
   			EditText EditText_Exterior_PhotoFront = (EditText) v.findViewById(R.id.Exterior_editText_photoFront);
   			EditText EditText_Exterior_PhotoRight= (EditText) v.findViewById(R.id.Exterior_editText_photoRight);    
   			EditText EditText_Exterior_PhotoBack= (EditText) v.findViewById(R.id.Exterior_editText_photoBack);
   			EditText EditText_Exterior_PhotoLeft= (EditText) v.findViewById(R.id.Exterior_editText_photoLeft);    
   			
            // Extracts the string value from the Edit text fields
   			String pictureFrontNote = EditText_Exterior_PhotoFront.getText().toString();
   			String pictureRightNote = EditText_Exterior_PhotoRight.getText().toString();
   			String pictureBackNote = EditText_Exterior_PhotoBack.getText().toString();
   			String pictureLeftNote = EditText_Exterior_PhotoLeft.getText().toString();
   			
   			// Creates array of updates needed
  	  		String[][] databaseUpdatesExteriorPhotos = {
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_FRONT,pictureFrontNote},
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_RIGHT,pictureRightNote},
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_BACK,pictureBackNote},
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_LEFT,pictureLeftNote}
					}; 
            
            // Updates the entries in the database
            updateStructureDB(databaseUpdatesExteriorPhotos);
   			
            break;
    // 	===============================================================================================  
            
   		case EXTRA_PHOTOS_TAB:
	// Extra Photos ==============================================================================
        	
   			// Declares the text input fields
   			EditText EditText_Extra_Picture1 = (EditText) v.findViewById(R.id.Extra_editText_Picture1);
   			EditText EditText_Extra_Picture2 = (EditText) v.findViewById(R.id.Extra_editText_Picture2);    
   			EditText EditText_Extra_Picture3 = (EditText) v.findViewById(R.id.Extra_editText_Picture3);
   			EditText EditText_Extra_Picture4 = (EditText) v.findViewById(R.id.Extra_editText_Picture4);    
   			EditText EditText_Extra_Picture5 = (EditText) v.findViewById(R.id.Extra_editText_Picture5); 
   			
            // Extracts the string value from the Edit text fields
   			String picture1Note = EditText_Extra_Picture1.getText().toString();
   			String picture2Note = EditText_Extra_Picture2.getText().toString();
   			String picture3Note = EditText_Extra_Picture3.getText().toString();
   			String picture4Note = EditText_Extra_Picture4.getText().toString();
   			String picture5Note = EditText_Extra_Picture5.getText().toString();
   			
   			// Creates array of updates needed
  	  		String[][] databaseUpdatesExtraPhotos = {
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_1,picture1Note},
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_2,picture2Note},
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_3,picture3Note},
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_4,picture4Note},
        			{SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_5,picture5Note}
					}; 
            
            // Updates the entries in the database
            updateStructureDB(databaseUpdatesExtraPhotos);
   			
        break;
    // 	===============================================================================================  
   			
   		default: // Update form tab ID was not found
   			// current does nothing
   			break;
   		}
       
    }

    public static String boolToString(Boolean b) {
    	  if (b)
    	    return "1";
    	  if (!b)
    	    return "0";
    	  throw new IllegalArgumentException(b+" is not a bool. Only 1 and 0 are.");
    }
      
      public static void updateStructureDB(String[][] databaseUpdates){
          // Push the changes to the database
          utilsHelper.openDatabase();
          utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID );
          utilsHelper.closeDatabase();
      }
    
    @Override
    protected Dialog onCreateDialog(int id) {
		
            switch (id) {

            case STRUCTURE_NOTE_DIALOG_ID:
            	AlertDialog.Builder builder = new AlertDialog.Builder(this);
                
                // Inflates the custom xml file layout create_structure_dialog.xml
                LayoutInflater inflater = this.getLayoutInflater();    
                View  dialogView  =  inflater.inflate(R.layout.structure_notes_dialog,null);
                builder.setView(dialogView);
                
                builder.setTitle(R.string.structure_notes_dialog_title);
                //builder2.setIcon(R.drawable.icon);    
                
                final EditText EditText_structureNotes = (EditText) dialogView.findViewById(R.id.structureNotes);     
                
                builder.setPositiveButton(R.string.save,
                		          
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            
                                        	// Defines strings input in by the user
                                            String structureNotes = EditText_structureNotes.getText().toString();
                                        	
                                            // Updates the user-defined structure to  the database
                                            //structureID = adapter.getCursor().getInt(adapter.getCursor().getColumnIndex(SqlHelper.COLUMN_ID));
                                            String[][] databaseUpdates = {
                                                    {SqlHelper.COLUMN_STRUCTURE_NOTES, structureNotes} 
                                                    };

                                            utilsHelper.openDatabase();                	
                                            utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID );
                                            structureCursor = utilsHelper.getStructureCursor(structureID);
                                           // utilsHelper.closeDatabase();                	
                                            
                                            return;
                                        }
                                });

                builder.setNegativeButton(android.R.string.cancel,
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {                                                   
                                                return;
                                        }
                                });    
                
                Dialog structureDialogEdit = builder.create();

                return structureDialogEdit;
        }
            
            return null;
                                                  
    }
    
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {   	
 
        switch (id) { 
            case STRUCTURE_NOTE_DIALOG_ID:
            	
            	final EditText structureNotes = (EditText) dialog.findViewById(R.id.structureNotes);     
            	
        		//Clear the EditText fields
        		String oldNotes= structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTES));
        		
        		structureNotes.setText(oldNotes); 
        		structureNotes.requestFocus();
                break;            	
                
            default:
            	Log.d(LAYOUT_INFLATER_SERVICE, "Wrong Structure DIALOG ID");
            	break;
        }
    }
   
}
